package com.gitee.cnlongdb.server.threads.init;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.gitee.cnlongdb.basic.constant.ConcurrentDataMap;
import com.gitee.cnlongdb.basic.constant.LongDbConstant;
import com.gitee.cnlongdb.basic.entity.backups.LongdbBackupsEntity;
import com.gitee.cnlongdb.basic.entity.matchingrule.MatchingReadWrite;
import com.gitee.cnlongdb.server.config.LongdbConfigHandler;
import com.gitee.cnlongdb.server.connect.LongDbConnect;
import com.gitee.cnlongdb.server.connect.nettymission.LongdbNettyClient;

/**
 * 系统名称：MasterSlaveBackupThread
 * 模块名称：
 × 模块描述：开启【主从备份(Master-slave)】的监听
 × 功能列表：
 × 模块作者：ZOUYONG
 × 开发时间：2018年12月25日 上午10:51:11
 × 模块路径：com.gitee.cnlongdb.server.threads.init.MasterSlaveBackupThread
 */
public class MasterSlaveBackupThread extends Thread {

	private final Logger logger = (Logger) LoggerFactory.getLogger(MasterSlaveBackupThread.class);

	private LongDbConnect connect;
	public MasterSlaveBackupThread(LongDbConnect connect) {
		logger.debug(LongDbConstant.longdbDefaultName + "初始化[主从备份(Master-slave)监听]...");
		this.connect = connect;
	}
	
	@Override
	public void run() {
		try {
			// 获取备份机器列表
			List<MatchingReadWrite> matchingList = 
					LongdbConfigHandler.getMatchingRuleListByConnect(connect, LongDbConstant.longdbSlaveDataBase);
			if(CollectionUtils.isEmpty(matchingList)) {
				logger.debug(LongDbConstant.longdbDefaultName + "没有需要备份的从库配置信息...");
				return;
			}
			
			for (int j=0; j<matchingList.size(); j++) {
				MatchingReadWrite matchingRule = matchingList.get(j);
				if(connect.getDataBaseIp().equals(matchingRule.getDataBaseIp()) 
						&& connect.getDataBasePort() == matchingRule.getDataBasePort()) {
					matchingList.remove(j); j--;
					continue;
				}
			}
			if(CollectionUtils.isEmpty(matchingList)) { return; }
			
			try {
				Iterator<LongdbBackupsEntity> it = ConcurrentDataMap.longdbBackupsList.iterator();
				while(it.hasNext()) {
					LongdbBackupsEntity backpups = it.next();
					for (int j=0; j<matchingList.size(); j++) {
						MatchingReadWrite matchingRule = matchingList.get(j);
						try {
							Map<String, Object> requestMap = new HashMap<String, Object>();
							requestMap.put(backpups.getOperType(), backpups);
							// 发送网络消息
							LongdbNettyClient.sendNettyMessageByLongdb(matchingRule.getDataBaseIp(), matchingRule.getDataBasePort(), requestMap);
							backpups.getMatchingList().add(matchingRule); // 保存已备份的从库数据信息
						} catch(Exception e) {
							// 对于同步发生异常的，暂时不予处理；后续优化升级
							logger.error("主从数据备份异常, matching: {}, backpups： {}, error：{}", 
									JSON.toJSONString(matchingRule), JSON.toJSONString(backpups), e.getMessage());
						}
					}
					it.remove(); // 同步完成后，后续要将backpups保存到数据库备份日志文件中
				}
			} catch(Exception e) {
				logger.error("主从备份(Master-slave)操作异常:" + e.getMessage());
			}
			
		} catch(Exception e) {
			e.printStackTrace();
			logger.error("主从备份异常：{}", e.getMessage());
		}
	}
	
}
